package com.ncepu.jjojcodesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.ncepu.jjojcodesandbox.model.ExecuteCodeRequest;
import com.ncepu.jjojcodesandbox.model.ExecuteCodeResponse;
import com.ncepu.jjojcodesandbox.model.ExecuteMessage;
import com.ncepu.jjojcodesandbox.model.JudgeInfo;
import com.ncepu.jjojcodesandbox.utils.ProcessUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author simon_jiang
 * @version 1.0
 */
@Slf4j
public abstract class JavaCodeSandBoxTemplate implements CodeSandBox {


    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";
    private static final String GLOBAL_JAVA_CLASS_NAME = "Main.java";
    private static final long TIME_OUT = 5000L;
    private static final List<String> blackList = Arrays.asList("Files", "exec", "Thread.sleep");
    private static final WordTree WORD_TREE;

    static {
        WORD_TREE = new WordTree();
        WORD_TREE.addWords(blackList);
    }

    /**
     * 1. 把用户的代码保存为文件
     *
     * @param code 用户代码
     * @return
     */
    public File saveCodeToFile(String code) {
        //         * 1. 把用户的代码保存为文件
        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        // 判断全局目录是否存在，不存在就新建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        return FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
    }

    /**
     * 2、编译代码
     *
     * @param userCodeFile
     * @return
     */
    public ExecuteMessage compileCode(File userCodeFile) {
        //         * 2. 编译代码，得到class文件
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsolutePath());
        try {
            ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(compileCmd, "编译");
            if (executeMessage.getExitValue() != 0) {
                throw new RuntimeException("编译错误");
            }
            return executeMessage;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 3、执行文件，获得执行结果列表
     *
     * @param userCodeFile
     * @param inputList
     * @return
     */
    public List<ExecuteMessage> runFile(File userCodeFile, List<String> inputList) {
        //         * 3. 执行代码，得到输出结果
        String userCodeParentPath = userCodeFile.getParentFile().getAbsolutePath();
        List<ExecuteMessage> runExecuteMessageList = new ArrayList<>();
        for (String inputArgs : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8 -cp %s Main %s", userCodeParentPath, inputArgs);
            try {
                ExecuteMessage executeMessage = ProcessUtils.runProcessAndGetMessage(runCmd, "运行");
                System.out.println(executeMessage);
                runExecuteMessageList.add(executeMessage);
            } catch (Exception e) {
                throw new RuntimeException("执行错误" + e);
            }
        }
        return runExecuteMessageList;
    }

    /**
     * 4、获取输出结果
     *
     * @param runExecuteMessageList
     * @return
     */
    public ExecuteCodeResponse getOutputResponse(List<ExecuteMessage> runExecuteMessageList) {
        //         * 4. 收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outputList = new ArrayList<>();
        long maxTime = 0;
        for (ExecuteMessage executeMessage : runExecuteMessageList) {
            String errorExecuteMessage = executeMessage.getErrorMessage();
            if (errorExecuteMessage != null) {
                executeCodeResponse.setMessage(errorExecuteMessage);
                // 用户提交代码执行中出现错误
                executeCodeResponse.setStatus(3);
                break;
            }
            outputList.add(executeMessage.getMessage());
            Long time = executeMessage.getTime();
            if (time != null) {
                maxTime = Math.max(maxTime, time);
            }
        }
        // 正常运行结束
        if (outputList.size() == runExecuteMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutputList(outputList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setTime(maxTime);
//        judgeInfo.setMemory(0L);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        return executeCodeResponse;
    }

    /**
     * 5、删除文件
     *
     * @param userCodeFile
     * @return
     */
    public boolean delFile(File userCodeFile) {
        //         * 5. 文件清理，释放空间
        if (userCodeFile.getParentFile() != null) {
            boolean del = FileUtil.del(userCodeFile.getParentFile());
            System.out.println("删除文件：" + (del ? "成功" : "失败"));
            return del;
        }
        return true;
    }

    /**
     * 获取错误响应
     *
     * @param e
     * @return
     */
    private ExecuteCodeResponse getErrorResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutputList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        // 表示代码沙箱错误
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) {

        List<String> inputList = request.getInputList();
        String code = request.getCode();

        // 检查代码中是否包含黑名单中的命令
        FoundWord foundWord = WORD_TREE.matchWord(code);
        if (foundWord != null) {
            System.out.println("检测到非法字符：" + foundWord.getFoundWord());
            return null;
        }
        //         * 1. 把用户的代码保存为文件
        File userCodeFile = saveCodeToFile(code);
        //         * 2. 编译代码，得到class文件
        ExecuteMessage executeMessage = compileCode(userCodeFile);
        System.out.println("编译结果：" + executeMessage);
        //         * 3. 执行代码，得到输出结果
        List<ExecuteMessage> executeMessages = runFile(userCodeFile, inputList);
        //         * 4. 收集整理输出结果
        ExecuteCodeResponse outputResponse = getOutputResponse(executeMessages);
        //         * 5. 文件清理，释放空间
        boolean b = delFile(userCodeFile);
        if (!b) {
            log.error("deleteFile error, userCodeFilePath = {}", userCodeFile.getAbsolutePath());
        }
        return outputResponse;
    }

}


